<template>
    <div>
        <div class="n-layout-page-header">
            <n-card :bordered="false" title="企业信息">
                <template #header-extra>
                    <n-button type="primary" @click="handleEdit">更新</n-button>
                </template>
                <n-page-header v-if="showTenant">
                    <n-grid :cols="4">
                        <n-gi>
                            <n-statistic label="地址" :value="tenantInfo.tenantAddress" />
                        </n-gi>
                        <n-gi>
                            <n-statistic label="详细地址" :value="tenantInfo.detailedAddress" />
                        </n-gi>
                        <n-gi>
                            <n-statistic label="电话" :value="tenantInfo.tenantPhone" />
                        </n-gi>
                        <n-gi>
                            <n-statistic label="邮箱" :value="tenantInfo.tenantEmail" />
                        </n-gi>
                        <n-gi>
                            <n-statistic label="行业类别">
                                {{ industryType.find(obj => obj.dictKey === tenantInfo.tenantIndustryType)?.dictName }}
                            </n-statistic>
                        </n-gi>
                        <n-gi>
                            <n-statistic label="信用代码" :value="tenantInfo.tenantCreditCode" />
                        </n-gi>
                        <n-gi>
                            <n-statistic label="组织结构代码" :value="tenantInfo.tenantCode" />
                        </n-gi>
                        <n-gi>
                            <n-statistic label="营业执照">
                                <n-image width="100" v-if="tenantInfo.tenantBusinessLicense !== null"
                                    :src="tenantInfo.tenantBusinessLicense" />
                            </n-statistic>
                        </n-gi>
                    </n-grid>
                    <template #title>
                        <span style="text-decoration: none; color: inherit">{{ tenantInfo.tenantName }}</span>
                    </template>
                    <template #avatar>
                        <n-avatar v-if="tenantInfo.tenantDoorPhoto !== null" :src="tenantInfo.tenantDoorPhoto" />
                        <n-avatar v-if="tenantInfo.tenantDoorPhoto === null">{{
                            extractFirstCharacter(tenantInfo.tenantName)
                        }}</n-avatar>
                    </template>
                    <template #footer>
                        <p style="color: rgb(118, 124, 130);">企业简介</p>
                        <p>{{ tenantInfo.tenantDesc }}</p>
                    </template>
                </n-page-header>
            </n-card>
        </div>
        <n-card :bordered="false" class="mt-4 proCard" title="法人信息">
            <n-page-header v-if="showTenant">
                    <n-grid :cols="4">
                        <n-gi>
                            <n-statistic label="法人姓名" :value="tenantLegal.name" />
                        </n-gi>
                        <n-gi>
                            <n-statistic label="法人电话" :value="tenantLegal.mobile" />
                        </n-gi>
                        <n-gi>
                            <n-statistic label="证件类型">
                                {{ documentType.find(obj => obj.dictKey === tenantLegal.idType)?.dictName }}
                            </n-statistic>
                        </n-gi>
                        <n-gi>
                            <n-statistic label="证件号" :value="tenantLegal.idNumber" />
                        </n-gi>
                        <n-gi>
                            <n-statistic label="法人近照">
                                <n-image width="100" v-if="tenantLegal.recentPhoto !== null"
                                    :src="tenantLegal.recentPhoto" />
                            </n-statistic>
                        </n-gi>
                        <n-gi>
                            <n-statistic label="身份证正面">
                                <n-image width="100" v-if="tenantLegal.idCardUp !== null" :src="tenantLegal.idCardUp" />
                            </n-statistic>
                        </n-gi>
                        <n-gi>
                            <n-statistic label="身份证反面">
                                <n-image width="100" v-if="tenantLegal.idCardDown !== null" :src="tenantLegal.idCardDown" />
                            </n-statistic>
                        </n-gi>
                    </n-grid>
            </n-page-header>
        </n-card>

        <n-drawer v-model:show="showOuter" :width="720" @mask-click="resetForm">
            <n-drawer-content :title="editTitle" :native-scrollbar="false">
                <n-form :model="formParams" :rules="rules" ref="formRef" label-placement="top" :label-width="120"
                    class="py-4">
                    <n-divider title-placement="left">基本信息</n-divider>

                    <n-grid :cols="24" :x-gap="24">
                        <n-form-item-gi :span="12" label="租户名称" path="tenant.tenantName">
                            <n-input maxlength="150" show-count placeholder="请输入租户名称"
                                v-model:value="formParams.tenant.tenantName" />
                        </n-form-item-gi>
                        <n-form-item-gi :span="12" label="租户电话" path="tenant.tenantPhone">
                            <n-input maxlength="20" show-count placeholder="请输入租户电话"
                                v-model:value="formParams.tenant.tenantPhone" />
                        </n-form-item-gi>
                        <n-form-item-gi :span="12" label="租户地址" path="tenant.tenantAddress">
                            <n-cascader v-model:value="formParams.tenant.tenantAddress" placeholder="请选择" cascade
                                label-field="cityName" value-field="mergerName" :options="regions" check-strategy="child"
                                :show-path="true" />
                        </n-form-item-gi>
                        <n-form-item-gi :span="12" label="详细地址" path="tenant.detailedAddress">
                            <n-input maxlength="150" show-count placeholder="请输入详细地址"
                                v-model:value="formParams.tenant.detailedAddress" />
                        </n-form-item-gi>
                        <n-form-item-gi :span="12" label="租户邮箱" path="tenant.tenantEmail">
                            <n-input maxlength="100" show-count placeholder="请输入租户邮箱"
                                v-model:value="formParams.tenant.tenantEmail" />
                        </n-form-item-gi>
                        <n-form-item-gi :span="12" label="统一社会信用代码" path="tenant.tenantCreditCode">
                            <n-input maxlength="32" show-count placeholder="请输入统一社会信用代码"
                                v-model:value="formParams.tenant.tenantCreditCode" />
                        </n-form-item-gi>
                        <n-form-item-gi :span="12" label="行业类别" path="tenant.tenantIndustryType">
                            <n-select v-model:value="formParams.tenant.tenantIndustryType" placeholder="请选择行业类别"
                                :options="industryTypeOps" />
                        </n-form-item-gi>
                        <n-form-item-gi :span="12" label="组织机构代码" path="tenant.tenantCode">
                            <n-input maxlength="32" show-count placeholder="请输入组织机构代码"
                                v-model:value="formParams.tenant.tenantCode" />
                        </n-form-item-gi>
                        <n-form-item-gi :span="24" label="租户简介" path="tenant.tenantDesc">
                            <n-input maxlength="300" show-count type="textarea" :autosize="{
                                minRows: 3,
                                maxRows: 5
                            }" v-model:value="formParams.tenant.tenantDesc" filterable placeholder="请输入租户简介" />
                        </n-form-item-gi>
                        <n-form-item-gi :span="12" label="营业执照" path="tenant.tenantBusinessLicense">
                            <BasicUpload :action="`${uploadUrl}/moss-cloud-resource/resource/uploadFile`"
                                :headers="uploadHeaders" :data="{ type: 0 }" name="file" :width="100" :height="100"
                                @upload-change="uploadTenantBusinessLicenseChange" v-model:value="tenantBusinessLicense"
                                :maxNumber="1" helpText="单个文件不超过20MB，最多只能上传1个文件" />
                        </n-form-item-gi>
                        <n-form-item-gi :span="12" label="门头照" path="tenant.tenantDoorPhoto">
                            <BasicUpload :action="`${uploadUrl}/moss-cloud-resource/resource/uploadFile`"
                                :headers="uploadHeaders" :data="{ type: 0 }" name="file" :width="100" :height="100"
                                @upload-change="uploadTenantDoorPhotoChange" v-model:value="tenantDoorPhoto" :maxNumber="1"
                                helpText="单个文件不超过20MB，最多只能上传1个文件" />
                        </n-form-item-gi>
                    </n-grid>

                    <n-divider title-placement="left">法人信息</n-divider>
                    <n-grid :cols="24" :x-gap="24">
                        <n-form-item-gi :span="12" label="租户法人" path="tenantLegal.tenantUserId">
                            <n-select v-model:value="formParams.tenantLegal.tenantUserId" filterable placeholder="请选择法人"
                                :options="legalOptions" :loading="selectLoading" clearable remote @search="handleSearch" />
                        </n-form-item-gi>
                        <n-form-item-gi :span="12" label="证件类型" path="tenantLegal.idType">
                            <n-select v-model:value="formParams.tenantLegal.idType" placeholder="请选择证件类型"
                                :options="documentTypeOps" />
                        </n-form-item-gi>
                        <n-form-item-gi :span="24" label="证件证件号" path="tenantLegal.idNumber">
                            <n-input maxlength="32" show-count placeholder="请输入证件证件号"
                                v-model:value="formParams.tenantLegal.idNumber" />
                        </n-form-item-gi>
                        <n-form-item-gi :span="12" label="身份证人像面" path="tenantLegal.idCardUp">
                            <BasicUpload :action="`${uploadUrl}/moss-cloud-resource/resource/uploadFile`"
                                :headers="uploadHeaders" :data="{ type: 0 }" name="file" :width="100" :height="100"
                                @upload-change="uploadIdCardUpChange" v-model:value="idCardUp" :maxNumber="1"
                                helpText="单个文件不超过20MB，最多只能上传1个文件" />
                        </n-form-item-gi>
                        <n-form-item-gi :span="12" label="身份证国徽面" path="tenantLegal.idCardDown">
                            <BasicUpload :action="`${uploadUrl}/moss-cloud-resource/resource/uploadFile`"
                                :headers="uploadHeaders" :data="{ type: 0 }" name="file" :width="100" :height="100"
                                @upload-change="uploadIdCardDownChange" v-model:value="idCardDown" :maxNumber="1"
                                helpText="单个文件不超过20MB，最多只能上传1个文件" />
                        </n-form-item-gi>
                        <n-form-item-gi :span="24" label="法人近照" path="tenantLegal.recentPhoto">
                            <BasicUpload :action="`${uploadUrl}/moss-cloud-resource/resource/uploadFile`"
                                :headers="uploadHeaders" :data="{ type: 0 }" name="file" :width="100" :height="100"
                                @upload-change="uploadRecentPhotoChange" v-model:value="recentPhoto" :maxNumber="1"
                                helpText="单个文件不超过20MB，最多只能上传1个文件" />
                        </n-form-item-gi>
                    </n-grid>
                </n-form>
                <template #footer>
                    <n-space>
                        <n-button @click="handleCloseDrawer">
                            取消
                        </n-button>
                        <n-button type="primary" :loading="formBtnLoading" @click="confirmForm">
                            确定
                        </n-button>
                    </n-space>
                </template>
            </n-drawer-content>
        </n-drawer>
    </div>
</template>
<script lang="ts" setup>
import { ref, onMounted, unref, reactive } from 'vue';
import { useMessage, type FormRules } from 'naive-ui';
import { tenantInfo as ApiTenantInfo, updateTenant } from '@/api/system/tenant';
import { extractFirstCharacter, removeEmptyChildren } from '@/utils/convert';
import { dictGroup } from '@/api/system/dict';
import { useUser } from '@/store/modules/user';
import { regionTrees } from '@/api/system/region';
import { searchUser, usersById } from '@/api/system/user';
import { useGlobSetting } from '@/hooks/setting';
import { ResultEnum } from '@/enums/httpEnum';

const message = useMessage();
const userStore = useUser();
const tenantInfo: any = ref({});
const tenantLegal: any = ref({});
const documentType: any = ref([]);
const industryType: any = ref([]);
const documentTypeOps: any = ref([]);
const industryTypeOps: any = ref([]);
const showOuter = ref(false);
const formRef: any = ref(null);
const tenantBusinessLicense: any = ref([]);
const tenantDoorPhoto: any = ref([]);
const idCardUp: any = ref([]);
const idCardDown: any = ref([]);
const recentPhoto: any = ref([]);
const regions: any = ref([]);
const legalOptions: any = ref([]);
const selectLoading = ref(false);
const globSetting = useGlobSetting();
const { uploadUrl } = globSetting;
const formBtnLoading = ref(false);
const editTitle = ref('');
const currentTenant: any = ref();
const showTenant = ref<boolean>(false);
const defaultValueRef = () => ({
    tenant: {
        id: null,
        /*** 租户名称*/
        tenantName: '',
        /*** 租户地址*/
        tenantAddress: '',
        /*** 详细地址*/
        detailedAddress: '',
        /*** 租户电话*/
        tenantPhone: '',
        /*** 租户邮箱*/
        tenantEmail: '',
        /** * 营业执照*/
        tenantBusinessLicense: '',
        /*** 统一社会信用代码*/
        tenantCreditCode: '',
        /*** 门头照*/
        tenantDoorPhoto: '',
        /*** 行业类型*/
        tenantIndustryType: '',
        /*** 组织机构代码*/
        tenantCode: '',
        /*** 租户简介*/
        tenantDesc: '',
    },
    tenantLegal: {
        /** 租户法人用户ID */
        tenantUserId: '',
        /** 法人近照 */
        recentPhoto: '',
        /** 证件类型 */
        idType: '',
        /** 证件号 */
        idNumber: '',
        /** 身份证正面 */
        idCardUp: '',
        /** 身份证反面 */
        idCardDown: '',
    }
});
const rules: FormRules = {
    tenant: {
        tenantName: {
            required: true,
            trigger: ['blur', 'input'],
            message: '请输租户名称',
        },
        tenantAddress: {
            required: true,
            trigger: ['blur', 'input'],
            message: '请选择企业地址'
        },
        tenantPhone: {
            required: true,
            trigger: ['blur', 'input'],
            message: '请输入企业电话',
        },
        tenantEmail: {
            pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/, trigger: ['blur', 'input'], message: '请输入正确的邮箱'
        },
    },
    tenantLegal: {
        tenantUserId: {
            type: 'number',
            required: true,
            trigger: ['blur', 'select'],
            message: '请选择企业法人',
        },
    }
};
let formParams = reactive(defaultValueRef());
const uploadHeaders = reactive({
    timestamp: new Date().getTime(),
    Authorization: 'Bearer ' + userStore.getToken,
});
/**
 * 证件类型
 */
const getDocumentTypes = async () => {
    const data = await dictGroup({ dictGroup: 'document_type' });
    documentType.value = data;
    documentTypeOps.value = data.map(item => ({ label: item.dictName, value: item.dictValue }));
}
/**
 * 行业类别
 */
const getIndustryTypes = async () => {
    const data = await dictGroup({ dictGroup: 'Industry_type' });
    industryType.value = data;
    industryTypeOps.value = data.map(item => ({ label: item.dictName, value: item.dictValue }));
}
const resetForm = () => {
    formRef.value.restoreValidation();
    formParams = Object.assign(unref(formParams), defaultValueRef());
    // 营业执照
    tenantBusinessLicense.value = [];
    // 门头照
    tenantDoorPhoto.value = [];
    // 法人身份证人像面
    idCardUp.value = [];
    // 法人身份证国徽面
    idCardDown.value = [];
    // 法人近照
    recentPhoto.value = [];
}
const apiRegionTrees = async () => {
    const data = await regionTrees({});
    const tree = removeEmptyChildren(data);
    regions.value = tree;
}
/**
 * 营业执照上传
 */
const uploadTenantBusinessLicenseChange = (list: string[]) => {
    tenantBusinessLicense.value = list;
    formParams.tenant.tenantBusinessLicense = list[0];
}
/**
 * 门头照上传
 */
const uploadTenantDoorPhotoChange = (list: string[]) => {
    tenantDoorPhoto.value = list;
    formParams.tenant.tenantDoorPhoto = list[0];
}
/**
 * 法人身份证人像面上传
 */
const uploadIdCardUpChange = (list: string[]) => {
    idCardUp.value = list;
    formParams.tenantLegal.idCardUp = list[0];
}
/**
 * 法人身份证国徽面上传
 */
const uploadIdCardDownChange = (list: string[]) => {
    idCardDown.value = list;
    formParams.tenantLegal.idCardDown = list[0];
}
/**
 * 法人近照上传
 */
const uploadRecentPhotoChange = (list: string[]) => {
    recentPhoto.value = list;
    formParams.tenantLegal.recentPhoto = list[0];
}
/**
 * 搜索法人
 */
const handleSearch = async (query: string) => {
    selectLoading.value = true;
    const data = await searchUser({ name: query });
    const arry = data.map(item => ({ label: item.name, value: item.id }));
    legalOptions.value = arry;
    selectLoading.value = false;
}
const handleCloseDrawer = () => {
    showOuter.value = false;
    resetForm();
}
/**
 * 提交数据
 */
const confirmForm = (e: any) => {
    e.preventDefault();
    formBtnLoading.value = true;
    formRef.value.validate(async (errors) => {
        if (!errors) {
            let data = await updateTenant(formParams);
            if (data.code !== ResultEnum.SUCCESS) {
                const resultMsg = data.data ? data.data : '';
                message.error(data.mesg + '-' + resultMsg);
            }
            if (data.code === ResultEnum.SUCCESS) {
                message.success(data.mesg);
                showOuter.value = false;
                resetForm();
                loadTenantInfo();
            }
        } else {
            message.error('请填写完整信息');
        }
        formBtnLoading.value = false;
    });
}
/**
 * 新增编辑
 * @param current 
 * @param addStatus 
 */
async function handleEdit() {
    showOuter.value = true;
    editTitle.value = `更新${currentTenant.value.tenant.tenantName}信息`;
    // 企业信息
    formParams = Object.assign(formParams, currentTenant.value);
    // 企业法人
    const users = await usersById({ id: currentTenant.value.tenantLegal.tenantUserId });
    let userList: any = [];
    userList.push({ label: users.name, value: users.id });
    legalOptions.value = userList;
    // 营业执照
    if (currentTenant.value.tenant.tenantBusinessLicense) {
        let license: any = [];
        license.push(currentTenant.value.tenant.tenantBusinessLicense);
        tenantBusinessLicense.value = license;
    }
    // 门头照
    if (currentTenant.value.tenant.tenantDoorPhoto) {
        let doorPhoto: any = [];
        doorPhoto.push(currentTenant.value.tenant.tenantDoorPhoto);
        tenantDoorPhoto.value = doorPhoto;
    }
    // 法人身份证人像面
    if (currentTenant.value.tenantLegal.idCardUp) {
        let cardUp: any = [];
        cardUp.push(currentTenant.value.tenantLegal.idCardUp);
        idCardUp.value = cardUp;
    }
    // 法人身份证国徽面
    if (currentTenant.value.tenantLegal.idCardDown) {
        let cardDown: any = [];
        cardDown.push(currentTenant.value.tenantLegal.idCardDown);
        idCardDown.value = cardDown;
    }
    // 法人近照
    if (currentTenant.value.tenantLegal.recentPhoto) {
        let legalrecentPhoto: any = [];
        legalrecentPhoto.push(currentTenant.value.tenantLegal.recentPhoto);
        recentPhoto.value = legalrecentPhoto;
    }
}
const loadTenantInfo = async () => {
    const data = await ApiTenantInfo();
    currentTenant.value = data;
    tenantInfo.value = data.tenant;
    tenantLegal.value = data.tenantLegal;
}
onMounted(async () => {
    showTenant.value = false;
    loadTenantInfo();
    getDocumentTypes();
    getIndustryTypes();
    apiRegionTrees();
    showTenant.value = true;
});
</script>
  
<style lang="less" scoped></style>
  